package com.hqd.ch03.v23.aop.framework.autoproxy;

import com.hqd.ch03.v23.aop.Advisor;
import com.hqd.ch03.v23.factory.ListableBeanFactory;
import com.hqd.ch03.v23.utils.BeanFactoryUtils;

import java.util.ArrayList;
import java.util.List;

public class BeanFactoryAdvisorRetrievalHelper {
    private final ListableBeanFactory listableBeanFactory;

    private volatile String[] cachedAdvisorBeanNames;


    public BeanFactoryAdvisorRetrievalHelper(ListableBeanFactory listableBeanFactory) {
        this.listableBeanFactory = listableBeanFactory;
    }


    public List<Advisor> findAdvisorBeans() {
        String[] advisorNames = this.cachedAdvisorBeanNames;
        if (advisorNames == null) {
            advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                    this.listableBeanFactory, Advisor.class);
            this.cachedAdvisorBeanNames = advisorNames;
        }
        if (advisorNames.length == 0) {
            return new ArrayList<>();
        }

        List<Advisor> advisors = new ArrayList<>();
        for (String name : advisorNames) {
            if (isEligibleBean(name)) {
                //创建切面bean
                advisors.add(this.listableBeanFactory.getBean(name, Advisor.class));
            }
        }
        return advisors;
    }

    protected boolean isEligibleBean(String beanName) {
        return true;
    }
}
